版本: Vue.js v2.6.10
使用方式:
<html>
<head>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <!-- your HTML code with Vue-->
</body>
</html>
你發現了嗎? Vue對 array成員內容的異動是無響應的:
  <div id="app">
    array內容 -- {{ myArray }}
    <br>
    <input type="button" @click="myClick()">Click and view console</input>
  </div>
  <script>
    var vm = new Vue({
      el: '#app',
      data: {
        myArray: [1, 2, 3, 4, 5]
      },
      methods: {
        myClick() {
          this.myArray[1] += 100
          console.log(this.myArray, 'array內容改變了,但畫面沒有響應')
        },
      }
    });
  </script>
加個watch觀察一下...確定靜悄悄:
      watch: {
        myArray: {
          handler: function (vnew, vold) {
            console.log(vnew, 'watch it!');
          },
          deep: true //drill down sensor
        }
      },
開始解釋了...
這是JS的特性嘛~array參照沒變,還是原來那個...
不然改成 object試看看:
      ...
      object內容 -- {{ myObj }}
      ...
      
      data: {
        myObj: { id: 10, age: 20, year: 150, qty: 0 }
      },
      //....
      methods: {
        myClick() {
          this.myObj.qty += 100
          console.log(this.myObj, 'object內容改變了,響應正常')
        },
      }
人家對 object有響應哩!
怎解?
簡單,動一下本尊就行:
      methods: {
        myClick() {
          this.myArray[1] += 100
          //--------------
          let tmp = this.myArray
          this.myArray = [];
          this.myArray = tmp;
          //--------------
          console.log(this.myArray, 'array內容改變了,畫面響應了')
        },
      }
好像有點遜...
不然就抓個有響應的伴下水,看你要不要渲染
...暴力
      ...
      array內容 -- {{ myArray }} {{ cnt }}  <!--(3)-->
      ...
      
      data: {
        myArray: [1, 2, 3, 4, 5],
        cnt: 0  //(1)
      },
      //....
      methods: {
        myClick() {
          this.cnt++  //(2)
          this.myArray[1] += 100
          console.log(this.myArray, 'array內容改變了,畫面響應了')
        },
      }
原來這也是我到今天才發現 array不會響應的原因 (因為跟著其它的一起渲染了)
還有這個原因
      data: {
        myArray: [1, 2, 3, 4, {id: 5} ],   //(1)
      },
      //....
      methods: {
        myClick() {
          this.myArray[4].id += 100   //(2)
          console.log(this.myArray, 'array內容改變了,畫面響應了')
        },
      }
Vue對 Object真的比較有感覺...
網路上有更多解法:
https://pjchender.blogspot.com/2017/05/vue-vue-reactivity.html
解法整理: